package com.situ.day15;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.junit.Test;

public class ReflactDemo {
	
	@Test
	public void testClass() throws ClassNotFoundException {
		// 1.Class.forName(类路径)
		Class clazz1 = Class.forName("com.situ.day15.Student");
		// 2.类型.class
		Class clazz2 = Student.class;
		// 3.对象.getClass()
		Student student = new Student();
		Class clazz3 = student.getClass();
		
		System.out.println(clazz1 == clazz2);//true
		System.out.println(clazz1 == clazz3);//true
	}
	
	@Test
	public void testConstructor1() {
		Class clazz = Student.class;
		Constructor[] constructors = clazz.getDeclaredConstructors();
		for (Constructor constructor : constructors) {
			System.out.println(constructor);
			System.out.println(constructor.getName());//构造方法的名字
			System.out.println(constructor.getModifiers());//修饰符
		}
	}
	
	@Test
	public void testConstructor2() throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		Class clazz = Student.class;
		//得到指定参数的构造方法
		Constructor constructor = clazz.getDeclaredConstructor(String.class);
		System.out.println(constructor);
		constructor.setAccessible(true);//加上之后就可以访问私有构造方法
		//Student student1 = new Student("zhansgan");
		Student student = (Student) constructor.newInstance("zhansgan");
		System.out.println(student);
	}
	
	@Test
	public void testMethod() throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		//Student student = new Student();
		//student.setName("lisi");
		
		Class clazz = Class.forName("com.situ.day15.Student");
		//得到无参构造方法
		Constructor constructor = clazz.getConstructor();
		//调用newInstance实例化对象
		Student student = (Student) constructor.newInstance();
		//student.setName("lisi");
		Method method = clazz.getMethod("setName", String.class);
		method.invoke(student, "lisi");
		System.out.println(student);
	}
	
	
	
	
}
